package com.media.selector.media

import android.app.Activity
import android.content.Intent
import android.database.Cursor
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ObservableBoolean
import com.media.selector.BR
import com.media.selector.MediaSelector
import com.media.selector.R
import com.media.selector.databinding.ActivityMediaBinding
import com.media.selector.media.helper.MediaPath
import com.media.selector.media.helper.setToolbar
import com.media.selector.media.listener.OnMediaFragmentListener
import com.media.selector.media.model.AlbumCollection
import com.media.selector.media.model.SelectedCollection
import com.media.selector.media.model.SelectionSpec
import com.media.selector.media.model.entity.AlbumEntity
import com.media.selector.media.model.entity.MediaEntity
import com.media.selector.media.preview.MediaPreviewActivity
import com.media.selector.media.window.AlbumSwitchWindow

/**
 * date        ：2020/4/21
 * author      ：蒙景博
 * description ：相册
 */
class MediaActivity : AppCompatActivity(), AlbumCollection.AlbumCallbacks, OnMediaFragmentListener {

    companion object {
        const val MEDIA_PREVIEW_REQUEST_CODE = 200
    }

    private lateinit var mBinding: ActivityMediaBinding
    val mPreviewClickable = ObservableBoolean(false)
    private val mAlbumCollection by lazy { AlbumCollection(this) }
    private val mAlbumSwitchWindow by lazy { AlbumSwitchWindow(this) }

    private val mMediaFragment by lazy { MediaFragment.with() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_media)
        mBinding.lifecycleOwner = this
        mBinding.setVariable(BR.data, this)
        // 设置 Toolbar
        setToolbar(mBinding.mediaToolbar){ onBackPressed() }
        // 初始化 AlbumCollection
        mAlbumCollection.onCreate(savedInstanceState, this)
        // 设置列表Fragment
        setContentFragment()
        // 设置文件夹显示 Window
        setAlbumSwitchWindow()
        // 设置根据配置是否显示预览
        mBinding.mediaBottomContainer.visibility = if (SelectionSpec.with().showPreview) View.VISIBLE else View.GONE
    }

    private fun setContentFragment(){
        supportFragmentManager.beginTransaction().add(R.id.media_container, mMediaFragment, MediaFragment::class.simpleName).commitAllowingStateLoss()
        mMediaFragment.setOnMediaFragmentListener(this)
    }

    private fun setAlbumSwitchWindow() {
        mAlbumSwitchWindow.setOnAlbumItemClickListener { position ->
            mAlbumCollection.setStateCurrentSelection(position)
            mAlbumSwitchWindow.getCursor()?.moveToPosition(position)
            val mAlbum = mAlbumSwitchWindow.getCursor()?.let { AlbumEntity.valueOf(it) }
            mAlbum?.let {
                mBinding.mediaAlbumTitle.text = it.getDisplayName(this)
                onAlbumSelected(it)
            }
        }
        mAlbumSwitchWindow.setOnAlbumSwitchWindowStateListener {
            val mArrowRes = if (it) R.drawable.svg_media_down_arrow else R.drawable.svg_media_up_arrow
            mBinding.mediaAlbumWindowArrow.setImageResource(mArrowRes)
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mAlbumCollection.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        mAlbumCollection.onDestroy()
    }

    override fun onBackPressed() {
        setResult(Activity.RESULT_CANCELED)
        super.onBackPressed()
    }

    fun onClick(view: View) {
        when(view.id) {
            R.id.media_album_switch -> mAlbumSwitchWindow.showAsDropDown(mBinding.mediaToolbar)
            R.id.media_preview -> mMediaFragment.onMediaClick(true,0)
            R.id.media_confirm_action -> onConfirmApply()
        }
    }

    override fun onAlbumLoad(cursor: Cursor?) {
        // 设置默认选中相册
        mAlbumSwitchWindow.swapCursor(cursor)
        runOnUiThread {
            cursor?.let {
                it.moveToPosition(mAlbumCollection.getCurrentSelection())
                mAlbumSwitchWindow.setSelection(mAlbumCollection.getCurrentSelection())
                val mAlbum = AlbumEntity.valueOf(it)
                mBinding.mediaAlbumTitle.text = mAlbum.getDisplayName(this)
                onAlbumSelected(mAlbum)
            }
        }
    }

    override fun onAlbumReset() {
        mAlbumSwitchWindow.swapCursor(null)
    }

    private fun onAlbumSelected(album: AlbumEntity) {
        if (album.mCount == 0L) {
            Log.e(javaClass.simpleName, "暂无数据")
        } else {
            mMediaFragment.loadMedia(album)
        }
    }

    /**
     * 拍照
     */
    override fun onTakePhoto() {
        MediaSelector.with().takePhoto(this)
    }

    /**
     * 查看预览
     */
    override fun onMediaClick(clickType: Boolean, position: Int, all: Bundle, selected: Bundle) {
        MediaPreviewActivity.start(this, MEDIA_PREVIEW_REQUEST_CODE, clickType, position, all, selected)
    }

    /**
     * 选中状态改变
     */
    override fun onCheckedStateChanged(size: Int) {
        mPreviewClickable.set(size > 0)
        mBinding.mediaConfirmAction.isClickable = size > 0
        val mMaxSelectable = SelectionSpec.with().maxSelectable
        val mConfirmTxt = getString(R.string.media_confirm_action)
        mBinding.mediaConfirmAction.text = if (size > 0) String.format("$mConfirmTxt(%s/%s)", size, mMaxSelectable) else mConfirmTxt
    }

    /**
     * 确定使用
     */
    private fun onConfirmApply() {
        val mSelectedMedias = mMediaFragment.getSelectedMedias()
        val mSelectedUris = mSelectedMedias?.map { it.contentUri }
        val mSelectedPaths = mSelectedMedias?.map { MediaPath.getFilePath(this, it.contentUri) }
        setResult(Activity.RESULT_OK, Intent().apply {
            putParcelableArrayListExtra(MediaSelector.EXTRA_RESULT_SELECTION, mSelectedUris?.let { ArrayList(it) })
            putStringArrayListExtra(MediaSelector.EXTRA_RESULT_SELECTION_PATH, mSelectedPaths?.let { ArrayList(it) })
        })
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == MediaSelector.TAKE_PHOTO_REQUEST_CODE) { // 拍照结果回调
            val mMediaUri = data?.getStringExtra(MediaSelector.EXTRA_TAKE_PHOTO_RESULT)
            setResult(Activity.RESULT_OK, Intent().apply {
                putStringArrayListExtra(MediaSelector.EXTRA_RESULT_SELECTION_PATH, ArrayList(listOf(mMediaUri)))
            })
            finish()
        } else if (requestCode == MEDIA_PREVIEW_REQUEST_CODE) { // 媒体选择结果回调
            val mResultBundle = data?.getBundleExtra(MediaPreviewActivity.EXTRA_RESULT_BUNDLE)
            val mResultType = data?.getBooleanExtra(MediaPreviewActivity.EXTRA_RESULT_APPLY, false) ?: false
            val mSelectedMedias = mResultBundle?.getParcelableArrayList<MediaEntity>(SelectedCollection.STATE_SELECTION)
            if (!mResultType) {
                mMediaFragment.syncSelectedBundle(mResultBundle)
            } else {
                val mSelectedUris = mSelectedMedias?.map { it.contentUri }
                val mSelectedPaths = mSelectedMedias?.map { MediaPath.getFilePath(this, it.contentUri) }
                setResult(Activity.RESULT_OK, Intent().apply {
                    putParcelableArrayListExtra(MediaSelector.EXTRA_RESULT_SELECTION, mSelectedUris?.let { ArrayList(it) })
                    putStringArrayListExtra(MediaSelector.EXTRA_RESULT_SELECTION_PATH, mSelectedPaths?.let { ArrayList(it) })
                })
                finish()
            }
        }
    }
}